#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "lwip/sockets.h"
#include "esp_log.h"

static const char *TAG_TCP = "TCP_CONTROL";

#define TCP_PORT 8080

void tcp_control_task(void *pvParameters)
{
    struct sockaddr_in dest_addr;
    dest_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    dest_addr.sin_family = AF_INET;
    dest_addr.sin_port = htons(TCP_PORT);

    int listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    if (listen_sock < 0) {
        ESP_LOGE(TAG_TCP, "Unable to create socket: errno %d", errno);
        vTaskDelete(NULL);
        return;
    }

    int yes = 1;
    setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

    if (bind(listen_sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr)) != 0) {
        ESP_LOGE(TAG_TCP, "Socket bind failed: errno %d", errno);
        close(listen_sock);
        vTaskDelete(NULL);
        return;
    }

    if (listen(listen_sock, 1) != 0) {
        ESP_LOGE(TAG_TCP, "Error listening on socket: errno %d", errno);
        close(listen_sock);
        vTaskDelete(NULL);
        return;
    }

    ESP_LOGI(TAG_TCP, "TCP Control Server Started on port %d", TCP_PORT);

    while (true) {
        struct sockaddr_in client_addr;
        socklen_t addr_len = sizeof(client_addr);
        int sock = accept(listen_sock, (struct sockaddr *)&client_addr, &addr_len);
        if (sock < 0) {
            ESP_LOGE(TAG_TCP, "Unable to accept connection: errno %d", errno);
            continue;
        }

        ESP_LOGI(TAG_TCP, "Client connected");

        char rx_buffer[128];
        while (true) {
            int len = recv(sock, rx_buffer, sizeof(rx_buffer), 0);
            if (len <= 0) {
                ESP_LOGI(TAG_TCP, "Client disconnected");
                close(sock);
                break;
            }

            rx_buffer[len] = '\0';
            ESP_LOGI(TAG_TCP, "Received command: %s", rx_buffer);

            if (strncmp(rx_buffer, "capture", 7) == 0) {
                // 执行拍照操作
                ESP_LOGI(TAG_TCP, "Capturing photo...");
                // 调用你自己的处理函数
            }
        }
    }
}

void start_tcp_control_server()
{
    xTaskCreate(tcp_control_task, "tcp_control", 4096, NULL, 5, NULL);
}